import React, { useState, useEffect, useRef } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { createEditor } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';

const EnhancedRichTextEditor = ({
                                    initialContent = '',
                                    height = 400,
                                    placeholder = '请输入内容...',
                                    onChange,
                                    disabled = false
                                }) => {
    const [editor, setEditor] = useState(null);
    const [isDirty, setIsDirty] = useState(false); // 内容是否被修改
    const prevContentRef = useRef('');

    // 增强版工具栏配置 - 增加更多实用功能
    const toolbarKeys = [
        // 文本格式
        'bold', 'italic', 'underline', 'through',
        '|',
        'fontSize', 'fontColor', 'bgColor',
        '|',
        'header1', 'header2', 'header3', 'header4', 'paragraph',
        '|',
        // 列表和缩进
        'listOrdered', 'listUnordered', 'checklist',
        '|',
        'indent', 'delIndent',
        '|',
        // 对齐方式
        'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyJustify',
        '|',
        // 插入内容
        'link', 'uploadImage', 'insertVideo',
        '|',
        'insertTable', 'insertCode', 'quote', 'divider',
        '|',
        // 操作
        'undo', 'redo', 'clearStyle', 'fullScreen'
    ];

    // 菜单详细配置
    const menuConfig = {
        // 图片上传配置
        uploadImage: {
            maxFileSize: 2 * 1024 * 1024, // 2MB
            accept: ['image/jpeg', 'image/png', 'image/gif'],
            async customUpload(file, insertFn) {
                try {
                    // 实际项目中替换为真实的图片上传API
                    console.log('上传图片:', file);
                    // 模拟上传成功返回的图片URL
                    const imgUrl = `https://picsum.photos/800/500?random=${Math.random()}`;
                    insertFn(imgUrl, file.name);
                } catch (error) {
                    console.error('图片上传失败:', error);
                    alert('图片上传失败，请重试');
                }
            }
        },
        // 视频上传配置
        insertVideo: {
            async customUpload(file, insertFn) {
                try {
                    // 实际项目中替换为真实的视频上传API
                    console.log('上传视频:', file);
                    // 模拟视频URL
                    const videoUrl = 'https://example.com/sample-video.mp4';
                    insertFn(videoUrl);
                } catch (error) {
                    console.error('视频上传失败:', error);
                    alert('视频上传失败，请重试');
                }
            }
        },
        // 表格配置
        insertTable: {
            maxRow: 10,
            maxCol: 10
        },
        // 代码块配置
        insertCode: {
            languages: [
                { value: 'javascript', text: 'JavaScript' },
                { value: 'html', text: 'HTML' },
                { value: 'css', text: 'CSS' },
                { value: 'java', text: 'Java' },
                { value: 'python', text: 'Python' },
                { value: 'json', text: 'JSON' }
            ]
        }
    };

    // 初始化编辑器
    useEffect(() => {
        if (editor) return;

        const newEditor = createEditor({
            html: initialContent,
            config: { placeholder }
        });
        setEditor(newEditor);
        prevContentRef.current = initialContent;

        return () => {
            if (editor) {
                editor.destroy();
                setEditor(null);
            }
        };
    }, [editor, initialContent, placeholder]);

    // 处理内容变化
    const handleEditorChange = (editor) => {
        if (!editor || !onChange) return;

        const currentHtml = editor.getHtml();
        const trimmedHtml = currentHtml
            .replace(/<[^>]*>/g, '')
            .replace(/\s+/g, '').trim();

        // 更新修改状态
        if (currentHtml !== prevContentRef.current) {
            setIsDirty(true);
        } else {
            setIsDirty(false);
        }

        // 内容校验逻辑
        if (trimmedHtml) {
            onChange(currentHtml);
            prevContentRef.current = currentHtml;
        } else if (prevContentRef.current) {
            onChange('');
            prevContentRef.current = '';
        }
    };

    return (
        <div className="w-full border border-gray-200 rounded-md overflow-hidden shadow-sm">
            {/* 工具栏额外信息 */}
            <div className="flex items-center justify-between px-4 py-2 bg-gray-50 border-b text-sm">
        <span className="text-gray-500">
          {isDirty ? <span className="text-red-500">●</span> : '○'} 编辑状态
        </span>
                <span className="text-gray-500">
          {editor?.getText().length || 0} 个字
        </span>
            </div>

            {/* 工具栏 */}
            <Toolbar
                editor={editor}
                defaultConfig={{ toolbarKeys }}
                style={{ borderBottom: '1px solid #e8e8e8', padding: '5px' }}
                disabled={disabled}
            />

            {/* 编辑区域 */}
            <Editor
                editor={editor}
                defaultConfig={{
                    placeholder,
                    menuConfig,
                    readOnly: disabled,
                    // 配置粘贴过滤
                    pasteFilterStyle: true,
                    pasteIgnoreImg: false,
                }}
                style={{ height, overflowY: 'auto' }}
                onCreated={handleEditorChange}
                onChange={handleEditorChange}
                onDestroyed={() => setEditor(null)}
            />
        </div>
    );
};

export default EnhancedRichTextEditor;